package com.parlons.activities;

import android.annotation.SuppressLint;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.Window;
import android.widget.CursorAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;

import com.parlons.DatabaseServices;
import com.parlons.R;
import com.parlons.SmackServices;

import java.lang.reflect.Field;
import java.lang.reflect.Method;


public class MainActivity extends AppCompatActivity implements OnClickListener {
    public ChatFragment chatFragment;
    public FriendsFragment friendsFragment;
    public SettingsFragment settingsFragment;
    public static int selected;
    public static boolean hasUnread;

    /**
     * 3 tab bar buttons
     */
    private LinearLayout mTabBtnChat;
    private LinearLayout mTabBtnFriends;
    private LinearLayout mTabBtnSettings;
    /**
     * To manage the fragments
     */
    public static FragmentManager fragmentManager;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        fragmentManager = getFragmentManager();
        setTabSelected(1);
        setTabSelected(0);

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        /** change the action bar based on fragment */
        if (selected == 1)
            menu.findItem(R.id.action_add_friend).setVisible(true);
        else
            menu.findItem(R.id.action_add_friend).setVisible(false);
        setChatUnread();
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.action_add_friend: {
                // Add friend
                Intent i = new Intent(MainActivity.this, AddFriendActivity.class);
                startActivity(i);
                return true;
            }
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
            if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
                try {
                    Method m = menu.getClass().getDeclaredMethod(
                            "setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (Exception e) {
                }
            }
        }
        return super.onMenuOpened(featureId, menu);
    }

    private void setOverflowShowingAlways() {
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class
                    .getDeclaredField("sHasPermanentMenuKey");
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void initViews() {

        mTabBtnChat = (LinearLayout) findViewById(R.id.id_tab_bottom_chat);
        mTabBtnFriends = (LinearLayout) findViewById(R.id.id_tab_bottom_friends);
        mTabBtnSettings = (LinearLayout) findViewById(R.id.id_tab_bottom_settings);

        mTabBtnChat.setOnClickListener(this);
        mTabBtnFriends.setOnClickListener(this);
        mTabBtnSettings.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.id_tab_bottom_chat || id == R.id.btn_chat_name || id == R.id.btn_tab_bottom_chat) {
            setTabSelected(0);
            invalidateOptionsMenu();
            return;
        }
        if (id == R.id.id_tab_bottom_friends || id == R.id.btn_friends_name || id == R.id.btn_tab_bottom_friends) {
            setTabSelected(1);
            invalidateOptionsMenu();
            return;
        }
        if (id == R.id.id_tab_bottom_settings || id == R.id.btn_settings_name || id == R.id.btn_tab_bottom_settings) {
            setTabSelected(2);
            invalidateOptionsMenu();
        }
    }


    /**
     * set selected based on index
     */
    @SuppressLint("NewApi")
    private void setTabSelected(int index) {
        // reset the buttons
        resetBtn();
        selected = index;
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        hideFragments(transaction);
        switch (index) {
            case 0:
                /** chat fragment selected */
                ((ImageButton) mTabBtnChat.findViewById(R.id.btn_tab_bottom_chat))
                        .setImageResource(R.drawable.btn_chat_pressed);
                if (chatFragment == null) {
                    chatFragment = new ChatFragment();
                    transaction.add(R.id.frag_content, chatFragment);
                } else {
                    transaction.show(chatFragment);
                }
                setTitle("Chat");
                break;
            case 1:
                /** friends fragment selected */
                ((ImageButton) mTabBtnFriends.findViewById(R.id.btn_tab_bottom_friends))
                        .setImageResource(R.drawable.btn_friends_pressed);
                if (friendsFragment == null) {
                    friendsFragment = new FriendsFragment();
                    transaction.add(R.id.frag_content, friendsFragment);
                } else {
                    transaction.show(friendsFragment);
                }
                setTitle("Friends");
                // start a thread to change UI
                new Runnable() {
                    @Override
                    public void run() {
                        while (FriendsFragment.simpleCursorAdapter == null) {
                            System.out.println("1 null");
                            try {
                                DatabaseServices DBService = DatabaseServices.getInstance(getApplicationContext());
                                Cursor cursor = DBService.getFriendsCursor(SmackServices.getUserName());
                                FriendsFragment.simpleCursorAdapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.friends_item, cursor, new String[]{"friend_username"}, new int[]{R.id.friends_list_username}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);


                            } catch (Exception e) {
                                e.printStackTrace();
                                return;
                            }
                        }

                        DatabaseServices DBService = DatabaseServices.getInstance(getApplicationContext());
                        Cursor cursor = DBService.getFriendsCursor(SmackServices.getUserName());
                        if (cursor == null)
                            System.out.println("cursor null");
                        FriendsFragment.simpleCursorAdapter.changeCursor(cursor);
                    }
                };


                break;
            case 2:
                /** settings fragment selected*/
                ((ImageButton) mTabBtnSettings.findViewById(R.id.btn_tab_bottom_settings))
                        .setImageResource(R.drawable.btn_settings_pressed);
                if (settingsFragment == null) {
                    settingsFragment = new SettingsFragment();
                    transaction.add(R.id.frag_content, settingsFragment);
                } else {
                    transaction.show(settingsFragment);
                }
                setTitle("Settings");
                break;
        }
        transaction.commit();
    }

    /**
     * Reset all the "selected" state
     */
    private void resetBtn() {
        ((ImageButton) mTabBtnChat.findViewById(R.id.btn_tab_bottom_chat))
                .setImageResource(R.drawable.btn_chat);
        ((ImageButton) mTabBtnFriends.findViewById(R.id.btn_tab_bottom_friends))
                .setImageResource(R.drawable.btn_friends);
        ((ImageButton) mTabBtnSettings.findViewById(R.id.btn_tab_bottom_settings))
                .setImageResource(R.drawable.btn_settings);
    }

    /**
     * hide all fragments
     *
     * @param transaction a fragment transaction
     */
    @SuppressLint("NewApi")
    private void hideFragments(FragmentTransaction transaction) {
        if (chatFragment != null) {
            transaction.hide(chatFragment);
        }
        if (friendsFragment != null) {
            transaction.hide(friendsFragment);
        }
        if (settingsFragment != null) {
            transaction.hide(settingsFragment);
        }

    }

    public void setChatUnread() {
        DatabaseServices DBService = DatabaseServices.getInstance(this);
        long totalUnread = DBService.getTotalUnread(SmackServices.getUserName());
        System.out.println("total unread : " + totalUnread);
        if (totalUnread != 0)
            MainActivity.hasUnread = true;
        else
            MainActivity.hasUnread = false;
        System.out.println("call setChatUnread");
        if (!hasUnread) {
            System.out.println("has no unread");
            if (selected == 0) { //selected
                ((ImageButton) mTabBtnChat.findViewById(R.id.btn_tab_bottom_chat))
                        .setImageResource(R.drawable.btn_chat_pressed);
            } else {
                ((ImageButton) mTabBtnChat.findViewById(R.id.btn_tab_bottom_chat))
                        .setImageResource(R.drawable.btn_chat);
            }
        } else {
            System.out.println("has unread");
            if (selected == 0) { //selected
                ((ImageButton) mTabBtnChat.findViewById(R.id.btn_tab_bottom_chat))
                        .setImageResource(R.drawable.btn_chat_pressed_new);
                System.out.println("selected");

            } else {
                System.out.println("not selected");
                ((ImageButton) mTabBtnChat.findViewById(R.id.btn_tab_bottom_chat))
                        .setImageResource(R.drawable.btn_chat_new);
            }
        }
    }


}
